package io.github.novaframe.security.jwt;

import io.github.novaframe.config.NovaframeProperties;
import io.github.novaframe.web.util.CookieUtil;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 接入系统SSO过滤器
 * @author xn045342
 * @date 2018/7/4
 */
public class JwtSsoFilter extends OncePerRequestFilter {

    // 注册filter
//    @Bean
//    public FilterRegistrationBean jwtFilter() {
//        final FilterRegistrationBean registrationBean = new FilterRegistrationBean();
//        registrationBean.setFilter(new JwtFilter());
//        registrationBean.setInitParameters(Collections.singletonMap("services.auth", authService));
//        registrationBean.addUrlPatterns("/protected-resource");
//        return registrationBean;
//    }

    private static final String jwtTokenCookieName = "JWT-TOKEN";
    private static final String signingKey = "signingKey";

    final NovaframeProperties properties;

    public JwtSsoFilter(NovaframeProperties properties) {
        this.properties = properties;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {

        // TODO 解析token
        String value = CookieUtil.getValue(httpServletRequest, jwtTokenCookieName);
        String username = null;
        if (username == null) {
            // 未认证跳转到认证服务
            String authService = properties.getSecurity().getSsoAuthUrl();
            httpServletResponse.sendRedirect(authService + "?redirect=" + httpServletRequest.getRequestURL());
        } else {
            // 已认证 放行
            httpServletRequest.setAttribute("username", username);
            filterChain.doFilter(httpServletRequest, httpServletResponse);
        }
    }
}
